/**
 * API版本管理中间件
 * 实现大厂级别的版本控制策略
 */

class VersionManager {
  constructor() {
    this.supportedVersions = {
      'v1': {
        version: '1.0',
        status: 'deprecated',
        deprecatedDate: '2024-01-01',
        sunsetDate: '2024-12-31',
        compatibility: 'legacy',
        features: ['basic-crud', 'simple-auth'],
        limitations: ['no-pagination', 'basic-validation']
      },
      'v2': {
        version: '2.0',
        status: 'stable',
        releaseDate: '2024-01-01',
        compatibility: 'current',
        features: ['enhanced-crud', 'advanced-auth', 'pagination', 'filtering', 'sorting'],
        breaking_changes: ['response-format', 'error-structure', 'validation-rules']
      },
      'v3': {
        version: '3.0',
        status: 'beta',
        releaseDate: '2024-06-01',
        compatibility: 'preview',
        features: ['graphql-support', 'real-time', 'advanced-analytics'],
        preview_notice: 'Subject to change without notice'
      }
    };

    this.defaultVersion = 'v2';
    this.latestVersion = 'v2';
  }

  /**
   * 版本检测中间件
   */
  detectVersion() {
    return (req, res, next) => {
      // 1. 从URL路径提取版本
      const pathVersion = this.extractVersionFromPath(req.path);
      
      // 2. 从Header提取完整版本
      const headerVersion = req.headers['x-api-version'] || req.headers['api-version'];
      
      // 3. 版本协商和验证
      const negotiatedVersion = this.negotiateVersion(pathVersion, headerVersion);
      
      // 4. 设置版本信息到请求对象
      req.apiVersion = {
        major: negotiatedVersion.major,
        minor: negotiatedVersion.minor,
        patch: negotiatedVersion.patch,
        full: negotiatedVersion.full,
        info: this.supportedVersions[negotiatedVersion.major]
      };

      // 5. 设置响应头
      this.setVersionHeaders(res, req.apiVersion);

      // 6. 版本警告处理
      this.handleVersionWarnings(req, res);

      next();
    };
  }

  /**
   * 从路径提取版本
   */
  extractVersionFromPath(path) {
    const versionMatch = path.match(/^\/api\/(v\d+)/);
    return versionMatch ? versionMatch[1] : null;
  }

  /**
   * 版本协商
   */
  negotiateVersion(pathVersion, headerVersion) {
    let majorVersion = pathVersion || this.defaultVersion;
    let fullVersion = headerVersion;

    // 验证主版本是否支持
    if (!this.supportedVersions[majorVersion]) {
      majorVersion = this.defaultVersion;
    }

    // 解析完整版本号
    if (fullVersion) {
      const versionParts = fullVersion.split('.');
      return {
        major: majorVersion,
        minor: versionParts[1] || '0',
        patch: versionParts[2] || '0',
        full: fullVersion
      };
    }

    // 使用默认版本
    const defaultInfo = this.supportedVersions[majorVersion];
    return {
      major: majorVersion,
      minor: '0',
      patch: '0',
      full: defaultInfo.version
    };
  }

  /**
   * 设置版本响应头
   */
  setVersionHeaders(res, versionInfo) {
    res.set({
      'X-API-Version': versionInfo.full,
      'X-API-Version-Major': versionInfo.major,
      'X-API-Status': versionInfo.info.status,
      'X-API-Supported-Versions': Object.keys(this.supportedVersions).join(', ')
    });

    // 添加弃用警告
    if (versionInfo.info.status === 'deprecated') {
      res.set({
        'X-API-Deprecated': 'true',
        'X-API-Sunset': versionInfo.info.sunsetDate,
        'Warning': `299 - "API version ${versionInfo.major} is deprecated. Please migrate to ${this.latestVersion}"`
      });
    }

    // 添加预览版本警告
    if (versionInfo.info.status === 'beta') {
      res.set({
        'X-API-Preview': 'true',
        'Warning': `299 - "API version ${versionInfo.major} is in preview. Subject to change without notice"`
      });
    }
  }

  /**
   * 版本警告处理
   */
  handleVersionWarnings(req, res) {
    const versionInfo = req.apiVersion.info;

    // 记录弃用版本的使用情况（用于数据分析）
    if (versionInfo.status === 'deprecated') {
      console.warn(`[VERSION_WARNING] Deprecated API ${req.apiVersion.major} used: ${req.method} ${req.path}`, {
        userAgent: req.headers['user-agent'],
        ip: req.ip,
        timestamp: new Date().toISOString()
      });
    }

    // 记录预览版本的使用情况
    if (versionInfo.status === 'beta') {
      console.info(`[VERSION_INFO] Preview API ${req.apiVersion.major} used: ${req.method} ${req.path}`, {
        timestamp: new Date().toISOString()
      });
    }
  }

  /**
   * 获取版本信息端点
   */
  getVersionInfo() {
    return (req, res) => {
      const currentVersion = req.apiVersion.major;
      const versionInfo = this.supportedVersions[currentVersion];

      res.json({
        current_version: req.apiVersion.full,
        version_info: versionInfo,
        supported_versions: this.supportedVersions,
        migration: {
          latest_stable: this.latestVersion,
          migration_guide: `/docs/migration/${currentVersion}-to-${this.latestVersion}`,
          breaking_changes: versionInfo.breaking_changes || [],
          compatibility_matrix: this.getCompatibilityMatrix()
        },
        deprecation_policy: {
          notice_period: '6 months',
          support_period: '18 months',
          sunset_process: 'Gradual feature removal with advance notice'
        }
      });
    };
  }

  /**
   * 获取兼容性矩阵
   */
  getCompatibilityMatrix() {
    return {
      'v1': {
        'v2': 'breaking_changes',
        'v3': 'not_compatible'
      },
      'v2': {
        'v1': 'backward_compatible',
        'v3': 'forward_compatible'
      },
      'v3': {
        'v1': 'not_compatible',
        'v2': 'backward_compatible'
      }
    };
  }

  /**
   * 版本迁移建议
   */
  getMigrationSuggestions(fromVersion, toVersion) {
    const migrations = {
      'v1-to-v2': {
        breaking_changes: [
          'Response format changed from simple object to standardized format',
          'Error codes now use structured format',
          'Authentication token format updated',
          'Pagination parameters changed'
        ],
        migration_steps: [
          'Update response parsing logic',
          'Handle new error format',
          'Update authentication headers',
          'Implement pagination support'
        ],
        automated_tools: [
          'Response transformer middleware',
          'Error format converter',
          'Authentication migrator'
        ]
      },
      'v2-to-v3': {
        breaking_changes: [
          'GraphQL endpoint introduction',
          'Real-time WebSocket support',
          'Enhanced filtering syntax'
        ],
        migration_steps: [
          'Evaluate GraphQL adoption',
          'Implement WebSocket handlers',
          'Update filter queries'
        ]
      }
    };

    return migrations[`${fromVersion}-to-${toVersion}`] || {
      message: 'No direct migration path available',
      recommendation: 'Migrate step by step through intermediate versions'
    };
  }
}

module.exports = new VersionManager();